import {IconPauseFill, IconPlayArrowFill} from "../../icons/index.js";

export function useProgress(audio, {
    setPlayState
}) {
    let progressElement;
    let currentTimeElement;
    let currentPointElement;
    let musicLyricsWrapper;

    function getSecondsByID(id) {
        const minutes = parseInt(id.substring(0, 2)) * 60;
        const seconds = +id.substring(3, id.length);
        const sec = minutes + seconds;
        return isNaN(sec) ? 0 : sec;
    }

    function timeupdate() {
        const currentTimeRate = audio.currentTime / audio.duration;
        const currentWidth = progressElement.clientWidth * currentTimeRate;
        currentTimeElement.style.width = `${currentWidth}px`;
        currentPointElement.style.left = `${currentWidth}px`;
        let latestLine;
        musicLyricsWrapper.querySelectorAll('.lyrics-line').forEach(line => {
            const time = getSecondsByID(line.id);
            if (!isNaN(time) && audio.currentTime > time) {
                latestLine = line;
            }
        });

        if (latestLine) {
            const activeLine = musicLyricsWrapper.querySelector('.lyrics-line.active');
            if (activeLine) {
                if (activeLine.id === latestLine.id) {
                    return;
                }
                activeLine.classList.remove('active');
            }

            latestLine.classList.add('active');

            console.log(latestLine.innerText);

            // musicLyricsWrapper.scrollTop = latestLine.offsetTop;
            musicLyricsWrapper.scrollTo({
                top: latestLine.offsetTop,
                behavior: "smooth",
            });
        }
    }

    audio.addEventListener('timeupdate', timeupdate);
    audio.addEventListener('loadedmetadata', () => {
        reset();
    });
    audio.addEventListener('error', (e) => {
        console.error("Error attempting to play", e);
    });

    function setCurrentTime(currentTime = 0, whenPaused = false) {
        audio.currentTime = currentTime;
        if (!whenPaused || !audio.paused) {
            audio.play();
            setPlayState(true);
        }
        timeupdate();
        updatePlayButton();
    }

    // 重置
    function reset() {
        setCurrentTime(0, true);
    }

    function updatePlayButton() {
        const playButton = document.querySelector('.footer .play-button');

        if (audio.paused) {
            playButton.innerHTML = IconPlayArrowFill({size: 32})
        } else {
            playButton.innerHTML = IconPauseFill({size: 32})
        }
    }

    function init() {
        progressElement = document.querySelector('.footer .progress');
        currentTimeElement = progressElement.querySelector('.current-time');
        currentPointElement = progressElement.querySelector('.current-point');
        musicLyricsWrapper = document.querySelector('.main .music-lyrics-wrapper');

        progressElement.addEventListener('click', (event) => {
            const currentTime = event.clientX / progressElement.clientWidth * audio.duration;
            setCurrentTime(parseFloat(currentTime.toFixed(6)));
        });
    }

    return {
        init,
        setCurrentTime,
        setCurrentTimeByID(id) {
            setCurrentTime(getSecondsByID(id))
        },
    }
}